package walkera.cn.tool;
import java.util.HashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import walkera.cn.bean.HeartBeatTask;

public class WkHeartBeatTool {
    private ScheduledExecutorService mScheduledExecutorService;
    private HashMap<String, Future > map  ;

    public WkHeartBeatTool() {
        initTool();
    }

    public int getTaskNum(){
        return map==null? 0 : map.size() ;
    }

    private void initTool() {
        mScheduledExecutorService = Executors.newScheduledThreadPool(5);
        map = new HashMap<String, Future>() ;
    }

    public void startTheBeatAction(HeartBeatTask task , int period){
        if(map.containsKey(task.getTaskName())){
            return ;
        }
        Future  future = mScheduledExecutorService.scheduleAtFixedRate( task , 0, period, TimeUnit.MILLISECONDS);
        map.put(task.getTaskName() , future) ;

    }

    public void shutDownTheBeatAction(HeartBeatTask task ){
        Future future = map.get(task.getTaskName()) ;
        if(future!=null){
            future.cancel(true) ;
            map.remove(task.getTaskName()) ;
        }
    }


    public void startDelayedAction( HeartBeatTask task , int delayTime){
        mScheduledExecutorService.schedule( task, delayTime ,TimeUnit.MILLISECONDS );
    }

    public void shutDownAll() {
        if (mScheduledExecutorService != null) {
            mScheduledExecutorService.shutdownNow();
            mScheduledExecutorService = null;
        }
        map.clear();
        map=null ;
    }
}
